package com.test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * @author W.S.
 * @version v1.0.0
 * @description 测试3D打印到图片水印
 * @date Created in 2019/3/25 17:20
 */
public class Pic {



    public void draw(){
//        headY = getFontStrHigth(fsfont) * 4 + headY;
//
//        temp.append("证书第  ");
//        temp.append(num);
//        temp.append("  号");
//        // 切换小二 18pt
//        fsfont = fsfont.deriveFont(Font.BOLD,42f);
//        g2.setFont(fsfont);
//
//        headY = fixCertHight;
//        // headY += 150;
//
//        g2.drawString(temp.toString(), headX + getSingalFontStrWidth(ktfont) * 2, headY);
//
//        //重置换行,组织机构
//        temp.setLength(0);//清空
//        headY = headY - new Double(getFontStrHigth(ktfont) * 1.5).intValue();

        // BufferedImage image = getLogo("logo.png");

        int orgStartPosition = 780;
        // g2.drawImage(image, null, orgStartPosition, headY);
            /*
            fsfont = fsfont.deriveFont(Font.PLAIN,26f);

            temp.append(orgName);
            int orgStartPosition = 850;
            g2.setFont(fsfont);
            g2.drawString(temp.toString(), orgStartPosition, headY - 5); // -5 微调
            // 获取落款日期开始位置
            int nowDatePosition = (orgStartPosition + getFontStrWidth(fsfont, temp.toString()) / 2) - getFontStrWidth(fsfont, nowDate) / 2;

            headY = headY + getFontStrHigth(ktfont);
            temp.setLength(0);//清空
            temp.append(nowDate);
            g2.drawString(temp.toString(), nowDatePosition, headY + 5); // +5 微调
            */
    }

    /**
     * 按字体分类化文本和参数数据
     * @return
     */
    public List<Draw> getDrawStrList(){
        String name = "测试名";
        String classStartTime = "2019年4月1日";
        String classEndTime = "2019年7月31日";
        String clzName = "“国有企业新机遇、新挑战与新作为网络培训班”，";
        Double courseHour = 12.5;
        String courseHourStr = courseHour.toString()+"学时";
        Font ktfont= FontUtil.getFont("kaiti_gb2312.ttf",Font.BOLD,55f);
        Font htfont = FontUtil.getFont("simhei.ttf",Font.BOLD,48f);
        Font htfont_40 = FontUtil.getFont("simhei.ttf",Font.BOLD,45f);
        Font fsfont = SingletonFonts.getFanSongInstance();
        fsfont.deriveFont(Font.PLAIN);
        Font hwfont = SingletonFonts.getHuaWenXinWeiInstance();
        // Font ktfont = SingletonFonts.getKaiTiInstance();
        List<Draw> data = new LinkedList<Draw>();
        data.add(new Draw(name,null));
        data.add(new Draw("同志自",fsfont));
        data.add(new Draw(classStartTime,fsfont));
        data.add(new Draw("至",fsfont));
        data.add(new Draw(classEndTime,fsfont));
        data.add(new Draw("在本院参加",fsfont));
        data.add(new Draw(clzName,hwfont));
        data.add(new Draw("共计完成",fsfont));
        data.add(new Draw(courseHourStr,fsfont));
        data.add(new Draw("网络课程，",fsfont));
        data.add(new Draw("成绩合格，",fsfont));
        data.add(new Draw("准予结业。",fsfont));
        return data;
    }
    public BufferedImage getPic(int test){
        BufferedImage bi = null;
        try {
            String path = "/Users/wensai/Downloads/demo/tempnew.jpg";
            String outPath = "/Users/wensai/Downloads/demo/temptest-test9.jpg";
            int headX = 250;
            int indentHeadX = 70;
            int headY = 550;
            int row = 1800;
            bi = ImageIO.read(new File(path));
            Graphics2D g2 = (Graphics2D) bi.getGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.BLACK);
            List<Draw> drawStrList = this.getDrawStrList();
            int X = headX + indentHeadX;
            for(Draw entry : drawStrList){
                int maxLen = row-X;
                Map<String,Object> xyData = this.drawClassName2(entry.getFont(),entry.getTemStr(),maxLen,X,headY,g2);
                headY = (Integer) xyData.get("y");
                X = (Integer) xyData.get("x");
                String thisStr = entry.getTemStr();
                if(null != xyData.get("str")){
                    thisStr = (String) xyData.get("str");
                }
                X = this.getNextX(g2, thisStr, X);
            }
            // 打印证书编号
            Font fsfont = SingletonFonts.getFanSongInstance();
            headY = getFontStrHigth(fsfont) * 5 + headY;
            String num = "WD201907800042";
            String numString = "证书第  "+ num + "  号";
            // 切换小二 18pt
            fsfont = fsfont.deriveFont(Font.BOLD,42f);
            g2.setFont(fsfont);
            int bh = headX + getSingalFontStrWidth(fsfont) * 3;
            System.out.println("编号X："+bh);
            System.out.println("编号Y："+headY);
            g2.drawString(numString, bh, headY);
            // 打印发证时间
            String nowDate = "2019年11月31日";
            fsfont = FontUtil.getFont("fansong_gb2312.ttf",Font.PLAIN,40f);
            headY = headY + getFontStrHigth(fsfont);
            g2.setFont(fsfont);
            int faz = headX + getSingalFontStrWidth(fsfont) * 29;
            g2.drawString(nowDate, faz, headY);
            System.out.println("发证日期X："+faz);
            System.out.println("发证日期Y："+headY);
            this.getFontStrWidth(fsfont,"");
            //this.outImg(bi,outPath);
        } catch (IOException e) {








            e.printStackTrace();
        }

        return bi;
    }

    public int getNextX(Graphics2D g2,String drawString,int X){
        int thisWith = getFontStrWidth(g2.getFont(),drawString);
        int next = thisWith + X;
        return next;
    }

    private Map<String,Object> drawClassName2(Font font,String str,int maxLen,int headX,int headY,Graphics2D g2) {
        Map<String,Object> map = new HashMap<>();
        int startX = 250;
        int row = 1800;
        g2.setFont(font);
        if(getFontStrWidth(font, str) > maxLen) {

            // 第一行
            int charIndex = getFixedWidthStrIndex(font,str,maxLen);
            String row1 = str.substring(0,charIndex + 1);
            g2.drawString(row1, headX, headY);
            headY = headY + 100;
            System.out.println("huanhang:"+getFontStrHigth(font) * 2);
            // 第二行
            String row2 = str.substring(charIndex + 1,str.length());
            maxLen = row;
            return drawClassName2(font,row2,maxLen,startX,headY,g2);
        }else {
            g2.drawString(str, headX, headY);
        }
        map.put("str",str);
        map.put("x",headX);
        map.put("y", headY);
        return map;
    }

    public BufferedImage getPic() {

        String tempStr = "{0}同志自{1}至{2}在本院参加“{3}”，共计完成{4}网络课程，成绩合格，准予结业。";
        String name = "测";
        String classStartTime = "2019年4月1日";
        String classEndTime = "2019年7月31日";
        String clzName = "“‘一带一路’：国有企业新机遇、新挑战与新作为网络培训班”，";
        Double courseHour = 12.5;
        String courseHourStr = courseHour.toString()+"学时";
        String score = "";
        String orgName = "";
        StringBuilder temp = new StringBuilder();
        String path = "/Users/wensai/Downloads/demo/tempnew.jpg";
        String num = "";
        String nowDate = "";
        String outPath = "/Users/wensai/Downloads/demo/temptest-4.jpg";

        // 一般班级证书不会超过两行，为了兼容文字铺满图片居中
        // int maxLen = 900; // 图片最大文字区px长度
        int maxLen = 1550;

        try {
            int headX = 280;
            int indentHeadX = 100;
            int headY = 550;
            int douHeadX = 140;
            int douHeadY = 320;
            int row = 1540;
            int fixCertHight = 1014; // 证书编号及logo固定高度

            //Font size 单位pt

            // 仿宋
//            Font fsfont = getFont("fansong_gb2312.ttf",Font.BOLD,48f);//22f
//            // 华文新魏
//            Font hwfont = getFont("huawenxinwei.ttf",Font.BOLD,51f);//24f
            // 楷体加黑
            Font ktfontNoBlod = FontUtil.getFont("kaiti_gb2312.ttf",Font.PLAIN,48f);

            // 优化读取
            // 黑体
            Font htfont = getFont("simhei.ttf",Font.BOLD,48f);
            Font fsfont = SingletonFonts.getFanSongInstance();
            Font hwfont = SingletonFonts.getHuaWenXinWeiInstance();
            Font ktfont = SingletonFonts.getKaiTiInstance();
            //获取图片  //zdy.fastdfsUrl
            BufferedImage bi = ImageIO.read(new File(path));
            Graphics2D g2 = (Graphics2D) bi.getGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.BLACK);
            int nameWidth = 0;
            temp.append(name);
            g2.setFont(ktfont);
            g2.drawString(temp.toString(), headX, headY);
            int lashStrWith = getFontStrWidth(g2.getFont(),name);


            {
                temp.setLength(0);
                temp.append(name);
                g2.setFont(ktfont);
                int thisWith = getFontStrWidth(g2.getFont(),name);
                //判断是否需要换行
                g2.drawString(temp.toString(), headX, headY);
                // 开头+lastWith+间距
                int nextStartX = thisWith + headX+148;

            }
            temp.setLength(0);//清空
            temp.append("同志自");
            g2.setFont(ktfontNoBlod);
            g2.drawString(temp.toString(), headX + 148 + nameWidth, headY);
            int with1 = getFontStrWidth(g2.getFont(),temp.toString());
            int nextX = headX + 148 + nameWidth + with1;
            temp.setLength(0);//清空
            temp.append(classStartTime);
            temp.append("至");
            temp.append(classEndTime);
            g2.setFont(ktfont);
            g2.drawString(temp.toString(), nextX, headY);
            int with2 = getFontStrWidth(g2.getFont(),temp.toString());
            temp.setLength(0);//清空
            temp.append("在本院参加");
            g2.setFont(ktfontNoBlod);

            g2.drawString(temp.toString(), nextX+with2, headY);

            temp.setLength(0);//清空

            // 班级名称居中,
            temp.append(clzName);
            g2.setFont(hwfont);
            //换行
            headY = getFontStrHigth(ktfont) * 2 + headY;

            if(name.length() <= 5) {
                if (clzName.length() <= 28) {
                    // 计算x轴开始值
                    int classNameheadX = (2070 - getFontStrWidth(hwfont, clzName)) / 2;

                    if (classNameheadX < 0) {
                        // 超出一行
                        // 第一行
                        int charIndex = getFixedWidthStrIndex(hwfont, temp.toString(), maxLen - nameWidth * 2);
                        String row1 = temp.toString().substring(0, charIndex + 1);
                        classNameheadX = (2070 - getFontStrWidth(hwfont, row1)) / 2;
                        g2.drawString(row1, classNameheadX, headY);
                        headY = getFontStrHigth(hwfont) * 2 + headY;
                        // 第二行
                        String row2 = temp.toString().substring(charIndex + 1, temp.toString().length());
                        headY = drawClassName(hwfont, row2, maxLen, headX, headY, g2);
                    } else {
                        g2.drawString(temp.toString(), classNameheadX, headY);
                    }
                } else {
                    int i = -1;
                    i = clzName.contains("，") ? clzName.indexOf("，") : (clzName.contains(",") ? clzName.indexOf(",") : -1);

                    if (i != -1) {
                        int classNameheadX = (2070 - getFontStrWidth(hwfont, clzName)) / 2;
                        // 第一行
                        int charIndex = getFixedWidthStrIndex(hwfont, temp.substring(0, i + 1).toString(), maxLen - nameWidth * 2);
                        String row1 = temp.toString().substring(0, i + 1);
                        classNameheadX = (2070 - getFontStrWidth(hwfont, row1)) / 2;
                        g2.drawString(row1, classNameheadX, headY);
                        headY = getFontStrHigth(hwfont) * 2 + headY;
                        // 第二行
                        String row2 = temp.toString().substring(i + 1, temp.toString().length());
                        int className2headX = (2070 - getFontStrWidth(hwfont, row2)) / 2;
                        headY = drawClassName(hwfont, row2, maxLen, className2headX, headY, g2);
                    } else {
                        // 超过28个字符 并且没有逗号分隔, 取第（n-4）/2的字数处换行
//                        int charIndex = getFixedWidthStrIndex(hwfont, temp.substring(0, (temp.toString().length() - 4) / 2).toString(), maxLen - nameWidth * 2);
                        String row1 = temp.toString().substring(0, (temp.toString().length() + 4) / 2);
                        int classNameheadX = (2070 - getFontStrWidth(hwfont, row1)) / 2;
                        g2.drawString(row1, classNameheadX, headY);
                        headY = getFontStrHigth(hwfont) * 2 + headY;
                        // 第二行
                        String row2 = temp.toString().substring((temp.toString().length() + 4) / 2, temp.toString().length());
                        int className2headX = (2070 - getFontStrWidth(hwfont, row2)) / 2;
                        headY = drawClassName(hwfont, row2, maxLen, className2headX, headY, g2);
                    }
                }
            }else{
                // 以下是name长度大于5的=================================
                if (clzName.length() <= 28) {
                    // 计算x轴开始值
                    int classNameheadX = (2070 - getFontStrWidth(hwfont, clzName)) / 2;
                    g2.drawString(temp.toString(), classNameheadX, headY+10);
                } else {
                    int i = -1;
                    i = clzName.contains("，") ? clzName.indexOf("，") : (clzName.contains(",") ? clzName.indexOf(",") : -1);
                    if (i != -1) {
                        int classNameheadX = 0;
                        // 第一行
//                        int charIndex = getFixedWidthStrIndex(hwfont, temp.substring(0, i + 1).toString(), maxLen - nameWidth * 2);
                        String row1 = temp.toString().substring(0, i + 1);
                        classNameheadX = (2070 - getFontStrWidth(hwfont, row1)) / 2;
                        g2.drawString(row1, classNameheadX, headY + 10);
                        headY = getFontStrHigth(hwfont) * 2 + headY;
                        // 第二行
                        String row2 = temp.toString().substring(i + 1, temp.toString().length());
                        int className2headX = (2070 - getFontStrWidth(hwfont, row2)) / 2;
                        headY = drawClassName(hwfont, row2, maxLen, className2headX, headY + 5, g2);
                    } else {
                        // 超过28个字符 并且没有逗号分隔, 取第（n-4）/2的字数处换行
                        int charIndex = getFixedWidthStrIndex(hwfont, temp.substring(0, (temp.toString().length() - 4) / 2).toString(), maxLen - nameWidth * 2);
                        String row1 = temp.toString().substring(0, (temp.toString().length() + 4) / 2);
                        int classNameheadX = (2070 - getFontStrWidth(hwfont, row1)) / 2;
                        g2.drawString(row1, classNameheadX, headY + 10);
                        headY = getFontStrHigth(hwfont) * 2 + headY;
                        // 第二行
                        String row2 = temp.toString().substring((temp.toString().length() + 4) / 2, temp.toString().length());
                        int className2headX = (2070 - getFontStrWidth(hwfont, row2)) / 2;
                        headY = drawClassName(hwfont, row2, maxLen, className2headX, headY + 5, g2);
                    }
                }
            }
            // 换行
            headY = getFontStrHigth(ktfont) * 2 + headY;
            temp.setLength(0);//清空
            temp.append("学习期满, 共计");
            if(courseHour == courseHour.longValue()) {
                temp.append(courseHour.longValue());
            }else {
                temp.append(courseHour);
            }
            temp.append("学时, 成绩");
            temp.append(score);
            temp.append(", 准予结业。");
            g2.setFont(fsfont);
            g2.drawString(temp.toString(), headX, headY);
            temp.setLength(0);//清空

            this.outImg(bi,outPath);
            return bi;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }



    public void outImg(BufferedImage bufImg, String outImgPath){
        try {
            FileOutputStream outImgStream =new FileOutputStream(outImgPath);
            ImageIO.write(bufImg,"jpg", outImgStream);
            outImgStream.flush();
            outImgStream.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }



    private int drawClassName(Font font,String str,int maxLen,int headX,int headY,Graphics2D g2) {

        if(getFontStrWidth(font, str) > maxLen) {

            // 第一行
            int charIndex = getFixedWidthStrIndex(font,str,maxLen);
            String row1 = str.substring(0,charIndex + 1);
            g2.drawString(row1, headX, headY);
            headY = headY + getFontStrHigth(font) * 2;
            // 第二行
            String row2 = str.substring(charIndex + 1,str.length());
            drawClassName(font,row2,maxLen,headX,headY,g2);
        }else {
            // 计算x轴开始值
            // int classNameheadX = (1303 - getFontStrWidth(font, str)) / 2;
            g2.drawString(str, headX, headY);
            // headY = headY + getFontStrHigth(font) * 2;
        }
        return headY;
    }

    /**
     * 获取该字体字符串宽度
     * @param font
     * @param str
     * @return
     */
    public Integer getFontStrWidth(Font font,String str) {

        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
        // 整个字符串的宽度
        return fm.stringWidth(str);

    }

    /**
     * 获取该字体字符串宽度
     * @param font
     * @return
     */
    public Integer getSingalFontStrWidth(Font font) {

        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
        // 整个字符串的宽度
        return fm.stringWidth("单");

    }

    /**
     * 获取字体字符串高度
     * @param font
     * @return
     */
    public Integer getFontStrHigth(Font font) {

        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
        // 高度
        return fm.getHeight();
    }

    /**
     * 获取固定长度字符串对应的索引位置
     * @param font
     * @param str
     * @param width
     * @return
     */
    public Integer getFixedWidthStrIndex(Font font,String str,Integer width) {
        char[] array = str.toCharArray();
        int sumWidth = 0;
        for(int i = 0;i < array.length;i++) {
            char c= array[i];
            sumWidth += getFontStrWidth(font, new Character(c).toString());
            if(sumWidth > width) {
                return i-1;
            }
        }
        return -1;
    }


    /**
     * 读取字体文件
     * @param fontName
     * @param style
     * @param size
     * @return
     * @throws IOException
     */
    private Font getFont(String fontName,Integer style,float size) throws IOException{
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream(fontName);
        BufferedInputStream bis = new BufferedInputStream(stream);
        Font font = null;
        try {
            font = Font.createFont(Font.TRUETYPE_FONT, bis);
            if(style != null) {
                font = font.deriveFont(style,size);
            }else {
                font = font.deriveFont(size);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bis.close();
            stream.close();
        }
        return font;
    }
}
